package model;



import java.util.ArrayList;
import java.util.List;

import controller.ConnectionTester;
import model.environmentConfig.*;
import model.threads.Initiator;
import model.threads.Listener;

public class ConnectionManager {
	private Node simNode;
	private List<Listener> listeners;
	private List<Initiator> initiators;
	public ConnectionManager(){
		simNode = null;
		initiators = new ArrayList<Initiator>();
		listeners = new ArrayList<Listener>();
	}
	
	public ConnectionManager(EnvironmentConfiguration eC){
		simNode = eC.getSimulatingNode();
		initiators = new ArrayList<Initiator>();
		listeners = new ArrayList<Listener>();
		if(simNode != null){
			for(CommunicationChannel c:eC.getChannels()){
				if(simNode == eC.getNodes().get(c.getListeningNode())){
					listeners.add(new Listener(c));
				}
				if(simNode == eC.getNodes().get(c.getInitiatorNode())){
					Initiator i = new Initiator(eC.getNodes().get(c.getListeningNode()), c);
					initiators.add(i);
				}
			}
		}
		else{
			System.out.println("simNode not selected!");
		}
		
	}

	public void stop() {
		// TODO Kill all threads
		for(Listener l : listeners){
			l.end();
			l.interrupt();
		}
		for(Initiator i : initiators){
			i.end();
			i.interrupt();
		}
	}

	public void start() {
		System.out.println("Listeners:" + listeners.size());
		for(Listener l : listeners){
			l.start();
		}
		System.out.println("Initiators:" + initiators.size());
		for(Initiator i : initiators){
			i.start();
		}
	}
	
	//TODO add some event Listener Functionality to update the Canvas for each thread
}
